package top.codedance.iotp.common.util.db.sqlite;

import top.codedance.iotp.common.util.SystemUtil;
import top.codedance.iotp.common.util.db.JdbcUtil;
import org.apache.log4j.Logger;

import java.io.File;
import java.sql.*;
import java.util.Properties;

public class SQLiteJDBCUtils implements JdbcUtil {

    private static Logger logger = Logger.getLogger(SQLiteJDBCUtils.class);
    private Properties properties;
    private static Class<?> clazz;
    protected static Connection c;

    public SQLiteJDBCUtils(Class<?> clazz, Logger logger, Properties properties) {
        this.logger = logger;
        this.clazz = clazz;
        this.properties = properties;
    }

    /**
     * 获取连接
     */
    public Connection getConnection() {
        if(c == null) {
            try {
                Class.forName("org.sqlite.JDBC");
                String runtimeDirPath = SystemUtil.getRuntimeDirPath(clazz);
                String db = "iotServer.data";
                if (properties.containsKey("dbPath")) {
                    db = properties.getProperty("dbPath");
                }
                c = DriverManager.getConnection("jdbc:sqlite:" + runtimeDirPath + File.separator + db);
                logger.info("Opened database successfully");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return c;
    }

    public void returnConnection(Connection c) {}

    /**
     * 释放资源
     */
    public void destory() {}

}
